package com.bawei.module_home.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.mvi.base.BaseMVIFragment
import com.bawei.lib_common.utils.ScrollConflictUtils
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_storage.room.DBUtils
import com.bawei.lib_storage.room.HistoryManager
import com.bawei.module_home.R
import com.bawei.module_home.adapter.LooperAdapter
import com.bawei.module_home.adapter.VideoAdapter
import com.bawei.module_home.adapter.VideoSortAdapter
import com.bawei.module_home.databinding.FragmentHomeBinding
import com.bawei.module_home.home.intent.SimpleTypeIntent
import com.bawei.module_home.home.state.SimpleTypeState
import com.bawei.module_home.home.state.VideoState
import com.bawei.module_home.home.viewmodel.HomeViewModel
import com.bawei.module_home.search.SearchActivity
import com.google.gson.Gson
import kotlinx.coroutines.launch


class HomeFragment : BaseMVIFragment() {
    private lateinit var homeViewModel: HomeViewModel
    private val binding: FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }
    private lateinit var scrollHandler: Handler
    private lateinit var scrollRunnable: Runnable
    private var rewardHandler: Handler? = null
    private var rewardRunnable: Runnable? = null
    private var totalAmount = 0.00
    private var isRewardRunning = false

    lateinit var adapter_sort: VideoSortAdapter
    lateinit var adapter: VideoAdapter

    // 分页相关变量
    private var currentPage = 1
    private val pageSize = 10
    private var isLoading = false
    private var isLastPage = false
    private var currentChannelId = "" // 当前选中的频道ID

    override fun generateViewModel() {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun lazyLoad() {
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.simpleTypeFlow_.collect {
                    when (it) {
                        is SimpleTypeState.Init -> {
                            showMsg("初始化")
                        }
                        is SimpleTypeState.Empty -> {
                            showMsg("空")
                        }
                        is SimpleTypeState.Failed -> {
                            showMsg("失败")
                        }
                        is SimpleTypeState.SimpleTypeSuccess -> {
                            it.list?.let { list ->
                                adapter_sort.setData(list)
                                if (list.isNotEmpty()) {
                                    currentChannelId = list[0].channelid // 默认选中第一个频道
                                    loadData(currentChannelId, 1, true)
                                }
                            }
                        }
                    }
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.videoFlow_.collect {
                    when (it) {
                        is VideoState.Init -> {
                            showMsg("初始化")
                        }
                        is VideoState.Empty -> {
                            showMsg("空")
                            handleLoadComplete()
                            if (currentPage == 1) {
                                adapter.setData(emptyList())
                            }
                            isLastPage = true
                        }
                        is VideoState.Failed -> {
                            showMsg("失败")
                            handleLoadComplete()
                        }
                        is VideoState.VideoSuccess -> {
                            showMsg("成功")
                            handleLoadComplete()

                            it.list?.let { videoList ->
                                if (currentPage == 1) {
                                    adapter.setData(videoList)
                                } else {
                                    adapter.addData(videoList)
                                }

                                // 判断是否是最后一页
                                isLastPage = videoList.size < pageSize
                            }
                        }
                    }
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        // 发送意图获取分类数据
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.intents.send(SimpleTypeIntent.getSimpleType)
                homeViewModel.handleIntent()
            }
        }
    }

    override fun initView() {
        super.initView()




        // 搜索按钮
        binding.notice.setOnClickListener {
            val intent = Intent(requireContext(), SearchActivity::class.java)
            intent.putExtra("channelId", currentChannelId)
            startActivity(intent)
        }
        // 小铃铛
        binding.root.findViewById<ImageView>(R.id.iv_bell).setOnClickListener {
            Toast.makeText(requireContext(), "点击了小闹钟", Toast.LENGTH_SHORT).show()
        }
        // 初始化分类适配器
        adapter_sort = VideoSortAdapter { channel ->
            currentChannelId = channel
            currentPage = 1
            isLastPage = false
            loadData(channel, currentPage, true)
        }
        binding.rvSort.adapter = adapter_sort
        binding.rvSort.layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
        
        // 解决滑动冲突：水平滚动的RecyclerView与父容器的冲突
        ScrollConflictUtils.resolveHorizontalRecyclerViewInScrollView(binding.rvSort)

        // 初始化视频适配器
        adapter = VideoAdapter()
        binding.rv.adapter = adapter
        binding.rv.layoutManager = LinearLayoutManager(requireActivity())

        // 设置视频点击事件
        adapter.onItemClickListener = { videoEntity ->
            saveVideoHistory(videoEntity)
            navigateToVideoDetail(videoEntity)
        }

        // 设置下拉刷新
        binding.swipeRefreshLayout.setOnRefreshListener {
            currentPage = 1
            isLastPage = false
            isLoading = false  // 添加这行，确保重置加载状态

            // 2秒后自动停止刷新
            Handler(Looper.getMainLooper()).postDelayed({
                if (binding.swipeRefreshLayout.isRefreshing) {
                    binding.swipeRefreshLayout.isRefreshing = false
                    showMsg("刷新超时")
                    isLoading = false  // 确保超时后重置状态
                }
            }, 2000)

            loadData(currentChannelId, currentPage, true)
        }

        //为了实现无感加载的效果，所以使用了预加载机制，在用户接近列表底部前就开始加载数据：
        // 设置上拉加载更多
        binding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            private val threshold = 5 // 提前5个item开始加载
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
//
//                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
//                val visibleItemCount = layoutManager.childCount
//                val totalItemCount = layoutManager.itemCount
//                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
//
//                if (!isLoading && !isLastPage) {
//                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
//                        && firstVisibleItemPosition >= 0
//                        && totalItemCount >= pageSize) {
//                        loadMoreData()
//                    }
//                }

                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

                if (!isLoading && !isLastPage) {
                    if ((visibleItemCount + firstVisibleItemPosition + threshold) >= totalItemCount) {
                        loadMoreData()
                    }
                }
            }
        })

        // 跑马灯效果
        val texts = listOf("热播电影", "今日推荐长歌行", "搜搜你想看的")
        val looperAdapter = LooperAdapter(texts)
        binding.search.adapter = looperAdapter
        binding.search.layoutManager = LinearLayoutManager(requireActivity())
        setupAutoScroll(texts.size)
    }

    private fun loadData(channelId: String, page: Int, isRefresh: Boolean) {
        isLoading = true
        if (isRefresh) {
            binding.swipeRefreshLayout.isRefreshing = true
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.intents.send(
                    SimpleTypeIntent.getVideoType(
                        channel = channelId,
                        page = page,
                        pageSize = pageSize
                    )
                )
                homeViewModel.handleIntent()
            }
        }
    }

//    private fun loadMoreData() {
//        if (!isLoading && !isLastPage) {
//            isLoading = true
//            adapter.setLoading(true)  // 显示加载视图
//            currentPage++
//            loadData(currentChannelId, currentPage, false)
//        }
//    }
    //为无感加载做准备
private fun loadMoreData() {
    if (!isLoading && !isLastPage) {
        isLoading = true
        // 不再调用 adapter.setLoading(true)
        currentPage++
        loadData(currentChannelId, currentPage, false)
    }
}

private fun handleLoadComplete() {
    isLoading = false
    adapter.setLoading(false)

    // 立即停止刷新（不需要等待2秒）
    if (binding.swipeRefreshLayout.isRefreshing) {
        binding.swipeRefreshLayout.isRefreshing = false
    }
}

    // 自动滚动-跑马灯
    private fun setupAutoScroll(itemCount: Int) {
        scrollHandler = Handler(Looper.getMainLooper())
        val scrollDuration = 800L
        val stayDuration = 1500L

        scrollRunnable = object : Runnable {
            var currentPage = 0

            override fun run() {
                currentPage = (currentPage + 1) % itemCount

                val smoothScroller = PageFlipSmoothScroller(requireActivity())
                smoothScroller.targetPosition = currentPage
                binding.search.layoutManager?.startSmoothScroll(smoothScroller)

                scrollHandler.postDelayed(this, scrollDuration + stayDuration)
            }
        }

        scrollHandler.postDelayed(scrollRunnable, stayDuration)
    }

    override fun onDestroy() {
        super.onDestroy()
        scrollHandler.removeCallbacks(scrollRunnable)
        // 释放红包奖励动画定时器
        isRewardRunning = false
        rewardHandler?.removeCallbacks(rewardRunnable!!)
        // 停止进度条动画
        rewardRunnable?.run()
    }

    /**
     * 保存视频历史记录
     */
    private fun saveVideoHistory(videoEntity: com.bawei.module_home.home.model.entity.VideoEntity) {
        lifecycleScope.launch {
            try {
                // 获取当前用户ID
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }

                Log.d("HomeFragment", "准备保存视频历史记录:")
                Log.d("HomeFragment", "- 用户ID: '$userId'")
                Log.d("HomeFragment", "- 视频标题: '${videoEntity.title}'")
                Log.d("HomeFragment", "- 视频描述: '${videoEntity.description}'")
                Log.d("HomeFragment", "- 作者名称: '${videoEntity.name}'")

                // 检查数据库是否初始化
                try {
                    val db = DBUtils.getDB()
                    Log.d("HomeFragment", "数据库已初始化")
                } catch (e: Exception) {
                    Log.e("HomeFragment", "数据库未初始化: ${e.message}")
                    return@launch
                }

                // 检查用户登录状态
                val isLoggedIn = UserUtils.isUserLoggedIn()
                Log.d("HomeFragment", "用户登录状态: $isLoggedIn")

                // 保存历史记录
                HistoryManager.addVideoHistory(
                    userId, videoEntity.title, videoEntity.videomainimag, videoEntity.description, videoEntity.avatar_url, videoEntity.name, 0, lastPosition = 0L, videoId = videoEntity.id.toString(), videopath = videoEntity.videopath
                )
                Log.d("HomeFragment", "保存视频历史记录成功: ${videoEntity.title}, 用户ID: $userId")

                // 验证是否保存成功
                val historyList = HistoryManager.getHistoryListByUserId(userId)
                Log.d("HomeFragment", "保存后用户历史记录总数: ${historyList.size}")

            } catch (e: Exception) {
                Log.e("HomeFragment", "保存视频历史记录失败: ${e.message}", e)
                e.printStackTrace() // 打印完整的错误堆栈
            }
        }
    }
    
    /**
     * 跳转到视频详情页面
     */
    private fun navigateToVideoDetail(videoEntity: com.bawei.module_home.home.model.entity.VideoEntity) {
        // 这里可以使用ARouter跳转到视频详情页面
        com.alibaba.android.arouter.launcher.ARouter.getInstance().build("/detail/DetailActivity")
             .withString("detail", Gson().toJson(videoEntity))
             .navigation()
    }
}

class PageFlipSmoothScroller(context: Context) : LinearSmoothScroller(context) {
    override fun getVerticalSnapPreference(): Int = SNAP_TO_START

    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
        return 100f / displayMetrics.densityDpi
    }

    override fun onStop() {
        super.onStop()
    }

    override fun calculateDtToFit(
        viewStart: Int,
        viewEnd: Int,
        boxStart: Int,
        boxEnd: Int,
        snapPreference: Int
    ): Int {
        return boxStart + (boxEnd - boxStart) / 2 - (viewStart + (viewEnd - viewStart) / 2)
    }
}